﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Domain.ViewModels.DataAuditing;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using System.Linq.Expressions;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Componnent.Entities.Customer;
using WaterRevenueMS.Core.Service.Customer;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterBook;
using WaterRevenueMS.Componnent.Common;

namespace WaterRevenueMS.WebUI.Controllers
{
    //抄表数据审核
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class DataAuditingController : AdminController
    {
        [Import]
        private IMeterInfoService MeterInfoService { get; set; }

        [Import]
        private IMeterBookService MeterBookService { get; set; }

        [AdminLayout]
        public ActionResult Index()
        {
            var model = new DataAuditingModel();
            var MeterBookItems = MeterBookService.MeterBooks.Where(t => t.IsDeleted == false)
                                .Select(t => new MeterBookModel {
                                    id=t.Id,
                                    Biao_CMC=t.Biao_CMC
                                });
            foreach (var item in MeterBookItems)
            {
                model.Search.MeterBookItems.Add(new SelectListItem { Text = item.Biao_CMC, Value = item.id.ToString() });
            }
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterInfoService.MeterInfos.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterInfoService.MeterInfos.Where(expr).Select(t => new DataAuditingModel
            {
                Id = t.Id,
                CustomerName = t.Customer != null ? t.Customer.Hu_ZXM : "",
                CustomerNo=t.Customer!=null?t.Customer.Yong_HBH:"",
                MeterNo=t.Yi_BBH,
                Yong_LBC=(t.Du_SBC-t.Du_SSQ)

            }).OrderBy(t => t.Id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.CustomerName,
                            c.CustomerNo,
                            c.MeterNo,
                            c.Yong_LBC.ToString(),
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        //用量调整
        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult ConsumptionAdjust(int id)
        {
            var entity = MeterInfoService.MeterInfos.FirstOrDefault(t => t.Id == id);
            var model = new DataAuditingModel
            {
                Id = entity.Id,
                CustomerName = entity.Customer != null ? entity.Customer.Hu_ZXM : "",
                MeterNo = entity.Yi_BBH,
                Yong_LBC = 0
            };

            return PartialView(model);
        }

        [HttpPost]
        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult ConsumptionAdjust(DataAuditingModel model)
        {
            if (ModelState.IsValid)
            {
                model.IsWaterCharge = false;
                OperationResult result = MeterInfoService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult WaterChargeAdjust(int id)
        {
            var entity = MeterInfoService.MeterInfos.FirstOrDefault(t => t.Id == id);
            var model = new DataAuditingModel
            {
                Id = entity.Id,
                CustomerName = entity.Customer != null ? entity.Customer.Hu_ZXM : "",
                MeterNo = entity.Yi_BBH,
                Fei_YTX=0
            };
            return PartialView(model);
        }

        [HttpPost]
        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult WaterChargeAdjust(DataAuditingModel model)
        {
            if (ModelState.IsValid)
            {
                model.IsWaterCharge = true;
                OperationResult result = MeterInfoService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }

        private Expression<Func<MeterInfo, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterInfo> bulider = new DynamicLambda<MeterInfo>();
            Expression<Func<MeterInfo, Boolean>> expr = null;
            if ((!string.IsNullOrEmpty(Request["Biao_CSZ_No"])) && Request["Biao_CSZ_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Biao_CSZ_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Biao_CSZ_No==data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            Expression<Func<MeterInfo, Boolean>> tmpException = t => (t.Du_SBC - t.Du_SSQ) < 0;
            expr = bulider.BuildQueryAnd(expr, tmpException);
            return expr;
        }
    }
}
